package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.service.CartService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("cart")
public class cartController {

    @Autowired
    private CartService cartService;

    @PostMapping("add")
    public ResultInfo saveCartById(@RequestBody Cart cart) {
        Cart save = cartService.save(cart);
        return ResultInfo.success(save);
    }

    /**
     * 查找购物车
     * 每个用户只能查找自己的购物车
     *
     * @return
     */

    @GetMapping("list")
    public ResultInfo findCart() {
        List<Cart> carts = cartService.findAll();
        return ResultInfo.success(carts);
    }


    /**
     * 更新购物车
     *
     * @return
     */
    @PostMapping("sub")
    public ResultInfo deleteCartBy(@RequestBody Cart cartparam) {
//调用业务层更新
        Cart cart = cartService.update(cartparam);
        if (cart == null) {
            cartparam.setNumber(0);
            return ResultInfo.success(cartparam);
        }
        return ResultInfo.success(cart);
    }

    @DeleteMapping("clean")
    public ResultInfo clean() {
        cartService.delete();
        return ResultInfo.success(null);
    }

}
